package com.xiaobaili.utils;


import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

public class SignatureUtils {


    /**
     * 生成签名
     *
     * @param timestamp 时间戳
     * @param nonce     随机数
     * @param token     令牌
     * @return 加密后的签名
     */
    public static String getSignature(String timestamp, String nonce, String token) {

        // 1. 将token、timestamp、nonce三个参数进行字典序排序
        String[] arr = new String[]{token, timestamp, nonce};
        Arrays.sort(arr);

        // 2. 将三个参数字符串拼接成一个字符串
        StringBuilder content = new StringBuilder();
        for (String s : arr) {
            content.append(s);
        }

        // 3. 对拼接后的字符串进行sha1加密
        return sha1Encrypt(content.toString());
    }

    /**
     * 对字符串进行SHA-1加密
     *
     * @param str 待加密的字符串
     * @return 加密后的字符串
     */
    private static String sha1Encrypt(String str) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.update(str.getBytes());
            byte[] messageDigest = digest.digest();
            StringBuilder hexString = new StringBuilder();
            for (byte b : messageDigest) {
                String shaHex = Integer.toHexString(b & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 验证签名是否来自微信
     *
     * @param signature 微信传来的签名
     * @param timestamp 时间戳
     * @param nonce     随机数
     * @param token     令牌
     * @return 签名是否匹配
     */
    public static boolean checkSignature(String signature, String timestamp, String nonce, String token) {
        String generatedSignature = getSignature(timestamp, nonce, token);
        return generatedSignature != null && generatedSignature.equals(signature);
    }

}
